package com.zzz.common.security.service;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.zzz.common.core.constants.CacheConstants;
import com.zzz.common.core.constants.HttpConstants;
import com.zzz.common.core.constants.JwtConstants;
import com.zzz.common.core.domain.R;
import com.zzz.common.core.enums.ResultCode;
import com.zzz.common.core.enums.UserIdentity;
import com.zzz.common.redis.service.RedisService;
import com.zzz.common.core.utils.JwtUtils;
import com.zzz.common.core.domain.LoginUser;
import com.zzz.common.security.exception.ServiceException;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject: oj-project
 * @BelongsPackage: com.zzz.common.security.service
 * @Author: zhai
 * @CreateTime: 2025-09-25  17:19
 * @Description: TODO 封装令牌服务
 * @Version: 1.0
 */
@Slf4j
@Service
public class TokenService {

    @Autowired
    private RedisService redisService;

    /**
     * @description: 创建令牌并存储到Redis中
     * @author: zhai
     * @date: 2025/9/25 19:26
     * @param: [userId, secret, identity]
     * @return: java.lang.String
     **/
    public String createToken(Long userId, String secret, Integer identity, String nickName, String headImage) {
        log.info("创建token开始");
        Map<String, Object> claim = new HashMap<>();
        String userKey = UUID.fastUUID().toString();
        log.info("创建唯一标识：{}", userKey);
        claim.put(JwtConstants.LOGIN_USER_ID, userId);
        claim.put(JwtConstants.LOGIN_USER_KEY, userKey);
        log.info("创建claim，用户信息为：{}", claim);
        String token = JwtUtils.createToken(claim, secret);
        LoginUser loginUser = new LoginUser();
        loginUser.setIdentity(identity);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        log.info("创建loginUser保存到redis中，用户信息为：{}", loginUser);
        String key = getTokenKey(userKey);
        redisService.setCacheObject(key, loginUser, CacheConstants.EXPIRE_TIME, TimeUnit.MINUTES);
        log.info("保存信息成功");
        return token;
    }

    /**
     * @description: 延长令牌有效期   时机：在身份认证(网关认证)之后才会调用，并且在请求到达controller层之前
     * @author: zhai
     * @date: 2025/10/12 16:28
     * @param: [token]
     * @return: void
     **/
    public void extendToken(String token, String secret) {
        String userKey = getUserKey(token, secret);
        if (userKey == null) {
            log.error("解析token：{},出错",token);
            return;
        }
        String tokenKey = getTokenKey(userKey);

        Long expire = redisService.getExpire(tokenKey, TimeUnit.MINUTES);
        if (expire != null && expire < CacheConstants.REFRESH_TIME) {
            redisService.expire(tokenKey, CacheConstants.EXPIRE_TIME, TimeUnit.MINUTES);
        }
    }

    /**
     * @description: 获取令牌key
     * @author: zhai
     * @date: 2025/10/12 16:28
     * @param: [userKey]
     * @return: java.lang.String
     **/
    private String getTokenKey(String userKey) {
        return CacheConstants.LOGIN_TOKEN_KEY + userKey;
    }

    /**
     * @description: 从token中获取用户信息
     * @author: zhai
     * @date: 2025/10/14 17:28
     * @param: [token]
     * @return: void
     **/
    public LoginUser getLoginUser(String token, String secret) {
        log.info("解析token开始");
        String userKey = getUserKey(token, secret);
        if (userKey == null) {
            log.error("解析token：{},出错",token);
            return null;
        }
        log.info("解析token：{}，成功，\n用户key为：{}",token, userKey);
        return redisService.getCacheObject(getTokenKey(userKey), LoginUser.class);
    }

    /**
     * @description: 管理员登出
     * @author: zhai
     * @date: 2025/10/15 14:04
     * @param: [token, secret]
     * @return: void
     **/
    public boolean logout(String token, String secret) {
        log.info("用户登出: {}", token);
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        LoginUser loginUser = getLoginUser(token, secret);
        String userKey = getUserKey(token, secret);
        if (loginUser == null) {
            log.error("token错误");
            return false;
        }
        if (!Objects.equals(loginUser.getIdentity(), UserIdentity.ADMIN.getValue())) {
            log.error("用户不是管理员");
            return false;
        }
        redisService.deleteObject(userKey);
        log.info("用户登出成功");
        return true;
    }

    /**
     * @description: 普通用户退出登录
     * @author: zhai
     * @date: 2025/10/30 21:26
     * @param: []
     * @return: boolean
     **/
    public boolean deleteLoginUser(String token, String secret) {
        // 解析token
        String userKey = getUserKey(token, secret);
        if (userKey == null) {
            log.error("解析token出错");
            return false;
        }
        return redisService.deleteObject(getTokenKey(userKey));
    }


    /**
     * @description: 获取用户key
     * @author: zhai
     * @date: 2025/10/14 20:31
     * @param: [token, secret]
     * @return: java.lang.String
     **/
    public String getUserKey(String token, String secret) {
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息 解析payload中信息
            if (claims == null) {
                log.error("解析token：{},出错",token);
                return null;
            }
        } catch (Exception e) {
            log.error("解析token：{},出错",token, e);
            return null;
        }
        return JwtUtils.getUserKey(claims);
    }
    /**
     * @description: 获取用户id
     * @author: zhai
     * @date: 2025/10/14 20:31
     * @param: [token, secret]
     * @return: java.lang.String
     **/
    public Long getUserId(String token, String secret) {
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息 解析payload中信息
            if (claims == null) {
                log.error("解析token：{},出错",token);
                return null;
            }
        } catch (Exception e) {
            log.error("解析token：{},出错",token, e);
            return null;
        }
        return Long.valueOf(JwtUtils.getUserId(claims));
    }
}
